const path = require('path');
const fs = require('fs');
var exec = require('child_process').exec;
const iconv = require('iconv-lite');
iconv.skipDecodeWarning = true;

function resolve(dir) {
  return path.join(__dirname, dir)
}
const commonPath = resolve('../');
const basePath = resolve('/src/module/');
console.info(basePath)
console.info(commonPath)
var readDirs = fs.readdirSync(commonPath);
var scriptName = __filename.split('\\');
scriptName = scriptName[scriptName.length-2];
console.info(scriptName, '--------------------------');
const externals = ['.idea', scriptName];
readDirs.forEach(function(fileName) {
  var fullPath = commonPath + fileName;

  if (externals.includes(fileName)) {
    return;
  }
  if (!fileName.includes('-module')) return;

  console.info(fileName);
  if (fs.statSync(fullPath).isDirectory()) {
    console.info('读取文件夹：' + fullPath);
    let componentName = fileName.replace('-module', '');
    console.info('componentName:'+componentName)
    let cmd = 'yarn lib:build '+componentName+' ./src/components/index.vue';
    exec(cmd, { cwd: fullPath, encoding: 'buffer' }, (error, stdout, stderr) => {
      if (error) {
        console.log(fullPath, iconv.decode(Buffer.from(stderr, 'binary'), 'cp936'))
      } else {
        let cssName = componentName+'.css';
        let cssSourcePath =fullPath+'\\dist'+'\\'+cssName;
        let jsName =componentName+'.umd.js';
        let jsSourcePath =fullPath+'\\dist'+'\\'+jsName;
        console.log('success:'+fullPath+'\\dist'+'\\'+cssName);
        if (fs.existsSync(cssSourcePath)) {
          console.info('同步-'+cssSourcePath+'===>'+basePath+'\\'+cssName);
          fs.cp(cssSourcePath, basePath+'\\'+cssName, err => {
            if (err) console.error(err)
          })
        }
        if (fs.existsSync(jsSourcePath)) {
          console.info('同步-'+jsSourcePath+'===>'+basePath+'\\'+jsName);
          fs.cp(jsSourcePath, basePath+'\\'+jsName, err => {
            if (err)  console.error(err)
          })
        }
      }
    });
  }
});
